/**
 * 功能:
 * 作者:周逸健
 * 日期: 2023/11/1 16:08
 */
package com.cgnfz.crm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cgnfz.crm.entity.dto.ApproveHistory;
import com.cgnfz.crm.entity.dto.CustomerInfo;
import com.cgnfz.crm.entity.dto.EmployeeInfo;
import com.cgnfz.crm.entity.vo.request.CustomerVO;
import com.cgnfz.crm.entity.vo.response.CustomerResp;
import com.cgnfz.crm.entity.vo.response.item.CustomerRespItem;
import com.cgnfz.crm.mapper.CustomerMapper;
import com.cgnfz.crm.service.ApproveHistoryService;
import com.cgnfz.crm.service.CustomerService;
import com.cgnfz.crm.service.EmployeeService;
import com.cgnfz.crm.utils.DateUtils;
import com.cgnfz.crm.utils.SnowflakeIdGenerator;
import io.netty.util.internal.StringUtil;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, CustomerInfo> implements CustomerService {

    @Resource
    DateUtils dateUtils;

    @Resource
    SnowflakeIdGenerator generator;

    @Resource
    ApproveHistoryService approveHistoryService;

    @Resource
    EmployeeService  employeeService;

    /**
     * @param employeeId
     * @param customer
     * @return
     */
    @Override
    public CustomerResp selectPage(String employeeId, String customer, Long pageNum, Long pageSize) {
        Page<CustomerInfo> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<CustomerInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(!StringUtil.isNullOrEmpty(customer), CustomerInfo::getCustomer, customer).eq(!StringUtil.isNullOrEmpty(employeeId), CustomerInfo::getEmployeeId, employeeId);
        IPage<CustomerInfo> customerPage = this.baseMapper.selectPage(page, wrapper);
        CustomerResp customerResp = new CustomerResp(customerPage.getTotal(), customerPage.getCurrent(), customerPage.getSize(), customerPage.getPages(), null);
        List<CustomerRespItem> list = new ArrayList<>();
        for (CustomerInfo info : customerPage.getRecords()) {
            CustomerRespItem item = info.asViewObject(CustomerRespItem.class);
            if ("02".equals(info.getStatus())) {
                item.setEndlineDay(String.valueOf(dateUtils.getDaySub(new Date(), info.getEndline()) + 1));
            } else {
                item.setEndlineDay(null);
            }
            list.add(item);
        }
        customerResp.setList(list);
        return customerResp;


    }

    /**
     * @param customerVO
     * @return
     */
    @Override
    @Transactional
    public String insert(CustomerVO customerVO) {
        boolean exit = this.baseMapper.exists(Wrappers.<CustomerInfo>query().eq("customer", customerVO.getCustomer()));
        if (exit) {
            return "客户已存在";
        }

        //查询销售详情
        if (StringUtil.isNullOrEmpty(customerVO.getEmployeeId())) {
            return "销售员不能为空";
        }
        EmployeeInfo employeeInfo = employeeService.findAccountByIdOrPhone(customerVO.getEmployeeId());
        CustomerInfo customerInfo = new CustomerInfo();

        String id = String.valueOf(generator.nextId());
        BeanUtils.copyProperties(customerVO, customerInfo);
        customerInfo.setEmployeeId(employeeInfo.getEmployeeId());
        customerInfo.setEmployeeCompany(employeeInfo.getEmployeeCompany());
        customerInfo.setId(id);
        customerInfo.setStatus("01");
        customerInfo.setEndline(dateUtils.getDateAdd(customerVO.getEndline()));

        int insert = this.baseMapper.insert(customerInfo);

        ApproveHistory approveHistory = this.toAddApprove(customerVO, id);
        //审批记录表插入数据
        if (insert == 1) {
            this.approveHistoryService.insert(approveHistory);
            return null;
        } else {
            return "数据有误，新增失败";
        }
    }


    /**
     * @param customerVO
     * @return
     */
    @Override
    @Transactional
    public String updateByStatus(CustomerVO customerVO) {
        CustomerInfo info = new CustomerInfo();
        switch (customerVO.getStatus()) {
            case "01":
                BeanUtils.copyProperties(customerVO, info);
                info.setEndline(dateUtils.getDateAdd(customerVO.getEndline()));
                //删除原有审批记录再新增
                this.updateApproveHistory(customerVO);
                break;
            case "02":
                BeanUtils.copyProperties(customerVO, info);
                info.setCreateTime(new Date());
                //更新审批记录表
                this.approveHistoryService.updateByCustomerId(this.toUpdateApprove(customerVO, "01"));
                break;
            case "03":
                info.setStatus(customerVO.getStatus());
                info.setId(customerVO.getId());
                break;
            case "99":
                this.approveHistoryService.updateByCustomerId(this.toUpdateApprove(customerVO, "02"));
                this.baseMapper.deleteById(customerVO.getId());
                return null;
            default:
                return "审批状态有误";
        }
        int i = this.baseMapper.updateById(info);
        if (i == 1)
            return null;
        else
            return "数据有误，更新失败";

    }

    /**
     * @param employeeId
     * @return
     */
    @Override
    public CustomerResp myCustomer(String employeeId) {
        if (StringUtil.isNullOrEmpty(employeeId)) {
            log.error("employeeId is null");
            return null;
        }
        QueryWrapper<CustomerInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("employee_id", employeeId);
        List<CustomerInfo> customerInfos = this.baseMapper.selectList(wrapper);
        CustomerResp customerResp = new CustomerResp(customerInfos.size(), 1, customerInfos.size(), 1, null);
        List<CustomerRespItem> list = new ArrayList<>();
        for (CustomerInfo info : customerInfos) {
            CustomerRespItem item = info.asViewObject(CustomerRespItem.class);
            if ("02".equals(info.getStatus())) {
                item.setEndlineDay(String.valueOf(dateUtils.getDaySub(new Date(), info.getEndline()) + 1));
            } else {
                item.setEndlineDay(null);
            }
            list.add(item);
        }
        customerResp.setList(list);
        return customerResp;
    }

    /**
     * @param customer
     * @return
     */
    @Override
    public CustomerResp approveList(String customer) {
        QueryWrapper<CustomerInfo> wrapper = new QueryWrapper<>();
        wrapper.eq(!StringUtil.isNullOrEmpty(customer),"customer", customer).eq("status", "01");
        List<CustomerInfo> approveHistories = this.baseMapper.selectList(wrapper);
        CustomerResp customerResp = new CustomerResp(approveHistories.size(), 1, approveHistories.size(), 1, null);
        List<CustomerRespItem> list = new ArrayList<>();
        for (CustomerInfo info : approveHistories) {
            CustomerRespItem item = info.asViewObject(CustomerRespItem.class);
            item.setEndlineDay(String.valueOf(dateUtils.getDaySub(new Date(), info.getEndline()) + 1));
            list.add(item);
        }
        customerResp.setList(list);
        return customerResp;
    }

    private void updateApproveHistory(CustomerVO customerVO) {
        this.approveHistoryService.deleteByCustomerId(customerVO.getId());
        ApproveHistory approveHistory = this.toAddApprove(customerVO, customerVO.getId());
        this.approveHistoryService.insert(approveHistory);
    }


    private ApproveHistory toAddApprove(CustomerVO customerVO, String id) {
        ApproveHistory approveHistory = new ApproveHistory();
        long approveId = generator.nextId();
        approveHistory.setId(String.valueOf(approveId));
        approveHistory.setCustomer(customerVO.getCustomer());
        approveHistory.setCustomerId(id);
        approveHistory.setApplyEmployee(customerVO.getEmployee());
        approveHistory.setApplyEmployeeId(customerVO.getEmployeeId());
        approveHistory.setApplyDate(new Date());
        return approveHistory;
    }

    private ApproveHistory toUpdateApprove(CustomerVO customerVO, String approveType) {
        ApproveHistory approveHistory = new ApproveHistory();
        approveHistory.setCustomerId(customerVO.getId());
        approveHistory.setApproveEmployee(customerVO.getEmployee());
        approveHistory.setApproveEmployeeId(customerVO.getEmployeeId());
        approveHistory.setApproveDate(new Date());
        approveHistory.setApproveType(approveType);
        return approveHistory;

    }


}
